<template>
  <div class="canvas-container">
    <canvas id="fabric-canvas" />
  </div>
</template>

<script>
// import { fabric } from "fabric";
import fabric from "fabric";

export default {
  data() {
    return {
      canvas: null,
      baseImage: null,
      isDragging: false,
      lastPosX: 0,
      lastPosY: 0,
      backimg: require("@/assets/bg.png"), // 底图地址
    };
  },

  mounted() {
    console.log(fabric, "fabric");
    this.initCanvas();
    this.loadBaseImage(this.backimg);
  },

  beforeDestroy() {
    // 清理事件监听
    this.canvas.off("mouse:down", this.startDrag);
    this.canvas.off("mouse:move", this.drag);
    this.canvas.off("mouse:up", this.endDrag);
  },

  methods: {
    handleSelectItemValue(item, value) {
      console.log(item, value);
      console.log(
        new Set(this.imgArr.map((tig) => tig.modelId)).size ===
          this.imgArr.length
      );
      // 1.将对应的allObjects内的该对象imgtarget更新到最新选择
      const newImgTarget = this.imgArr.find((img) => img.modelId === value);
      if (newImgTarget) {
        // item.imgtarget = newImgTarget;
        this.$set(item, "imgtarget", newImgTarget); // 使用 $set 更新
        // 确保 id 不被修改
        console.log("Item id:", item.id); // 检查 id 是否正确
      }
      console.log(newImgTarget, "newImgTarget");
      console.log(this.allObjects, "1111");
      // 2.更新对应的画布中的对象的图片然后重新渲染画布，保证修改的allObjects中的对象和画布对应
      // if (item.fabricObject) {
      //   // 加载新图片
      //   console.log(2222);
      //   this.loadImage(newImgTarget.imageUrl).then((img) => {
      //     // 保存原对象的位置和角度
      //     console.log(img, "imgimg");
      //     const originalLeft = item.fabricObject.get("left");
      //     const originalTop = item.fabricObject.get("top");
      //     const originalAngle = item.fabricObject.get("angle");
      //     // 移除旧的 fabricObject
      //     this.canvas.remove(item.fabricObject);
      //     // 创建新的 fabric.Image 对象
      //     const newFabricImg = new fabric.Image(img, {
      //       left: originalLeft,
      //       top: originalTop,
      //       originX: "center",
      //       originY: "center",
      //       scaleX: item.width / img.width, // 基于原始尺寸计算缩放比例
      //       scaleY: item.height / img.height,
      //       selectable: true, // 图片可选中
      //       lockScalingX: true, // 禁止水平缩放
      //       lockScalingY: true, // 禁止垂直缩放
      //       angle: originalAngle, // 保留原旋转角度
      //       modelId: newImgTarget.modelId, // 更新 modelId
      //       originalSrc: newImgTarget.imageUrl, // 更新原始图片路径
      //     });
      //     console.log(newFabricImg, "newFabricImg");
      //     // 添加新的 fabricObject 到画布
      //     this.canvas.add(newFabricImg);
      //     // 设置选中状态
      //     this.canvas.setActiveObject(newFabricImg);
      //     // 更新 allObjects 中的 fabricObject 引用
      //     item.fabricObject = newFabricImg;
      //     // 更新文字位置和角度
      //     if (item.textObject) {
      //       item.textObject.set({
      //         left: originalLeft,
      //         top: originalTop,
      //         angle: originalAngle,
      //       });
      //       item.textObject.visible = this.isTextVisible;
      //       console.log(item.textObject, "texttext");
      //     }
      //     // 更新箭头位置和角度
      //     if (item.arrowObject) {
      //       this.updateArrowPosition(newFabricImg);
      //     }
      //     // 画布渲染
      //     this.canvas.requestRenderAll();
      //   });
      // }
    },
    initCanvas() {
      // 创建画布
      this.canvas = new fabric.Canvas("fabric-canvas", {
        selection: false,
        preserveObjectStacking: true,
        fireRightClick: true,
      });

      // 设置容器尺寸
      const container = document.querySelector(".canvas-container");
      this.canvas.setWidth(container.clientWidth);
      this.canvas.setHeight(container.clientHeight);

      // 添加事件监听
      this.canvas.on("mouse:down", this.startDrag);
      this.canvas.on("mouse:move", this.drag);
      this.canvas.on("mouse:up", this.endDrag);

      // 添加滚轮缩放
      this.canvas.on("mouse:wheel", this.handleMouseWheel);
    },

    async loadBaseImage(imgUrl) {
      try {
        // 加载底图
        this.baseImage = await new Promise((resolve, reject) => {
          fabric.Image.fromURL(imgUrl, (img) => {
            img.set({
              left: 0,
              top: 0,
              selectable: false,
              evented: false,
              lockMovementX: true,
              lockMovementY: true,
              lockScalingX: true,
              lockScalingY: true,
              hasControls: false,
              hasBorders: false,
            });
            resolve(img);
          });
        });

        // 添加元素到画布
        this.canvas.add(this.baseImage);
        this.addCoordinateAxes();
        this.centerViewport();
      } catch (error) {
        console.error("Error loading image:", error);
      }
    },

    addCoordinateAxes() {
      // 创建坐标轴
      const xAxis = new fabric.Line([0, 0, 2000, 0], {
        stroke: "red",
        strokeWidth: 2,
        selectable: false,
        evented: false,
      });

      const yAxis = new fabric.Line([0, 0, 0, 2000], {
        stroke: "red",
        strokeWidth: 2,
        selectable: false,
        evented: false,
      });

      this.canvas.add(xAxis, yAxis);
    },

    centerViewport() {
      // 居中显示底图
      const imgWidth = this.baseImage.width;
      const imgHeight = this.baseImage.height;
      const canvasWidth = this.canvas.getWidth();
      const canvasHeight = this.canvas.getHeight();

      // 计算缩放比例
      const scale = Math.min(canvasWidth / imgWidth, canvasHeight / imgHeight);

      // 设置初始缩放和位置
      this.canvas.setZoom(scale);
      this.canvas.viewportTransform[4] = (canvasWidth - imgWidth * scale) / 2;
      this.canvas.viewportTransform[5] = (canvasHeight - imgHeight * scale) / 2;
    },

    handleMouseWheel(opt) {
      // 鼠标滚轮缩放
      const delta = opt.e.deltaY;
      let zoom = this.canvas.getZoom();
      zoom *= 0.999 ** delta;
      zoom = Math.min(Math.max(zoom, 0.1), 5); // 限制缩放范围

      this.canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom);
      opt.e.preventDefault();
      opt.e.stopPropagation();
    },

    startDrag(opt) {
      // 开始拖动
      this.isDragging = true;
      this.lastPosX = opt.e.clientX;
      this.lastPosY = opt.e.clientY;
    },

    drag(opt) {
      if (!this.isDragging) return;

      // 计算移动距离
      const deltaX = opt.e.clientX - this.lastPosX;
      const deltaY = opt.e.clientY - this.lastPosY;

      // 根据当前缩放系数调整移动速度
      const zoom = this.canvas.getZoom();
      const newTransform = [...this.canvas.viewportTransform];
      newTransform[4] += deltaX / zoom;
      newTransform[5] += deltaY / zoom;

      this.canvas.setViewportTransform(newTransform);

      // 更新位置记录
      this.lastPosX = opt.e.clientX;
      this.lastPosY = opt.e.clientY;
    },

    endDrag() {
      this.isDragging = false;
    },
  },
};
</script>

<style scoped>
.canvas-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #f0f0f0;
}

#fabric-canvas {
  touch-action: none; /* 防止移动端默认行为 */
}
</style>
